package plgbase

import (
	"dgo/goutils/utils"
	"fmt"
	"gitee.com/ymofen/gobase"
	"os"
	"strings"
)

func PlgReplacePlaceholder(s string) string {
	start := "$$"
	end := "$$"
	idx := 0
	var replkey string

	for {
		id := utils.GetBetween(s, start, end, idx)
		if len(id) == 0 {
			break
		}

		rawrepl := id

		// env.cpyidx % 10
		if ok, id := gobase.CheckTrimPrefix(id, "env."); ok { // 环境变量
			isObject, id := utils.CheckTrimSuffix(id, ".object")
			strv := os.Getenv(id)
			if isObject {
				replkey = fmt.Sprintf("\"%s%s%s\"", start, rawrepl, end)
			} else {
				replkey = fmt.Sprintf("%s%s%s", start, rawrepl, end)
				strv = utils.EscapeJsonStrSimple(strv)
			}
			s = strings.ReplaceAll(s, replkey, strv)
			continue
		}

		isObject, id := utils.CheckTrimSuffix(id, ".object")
		if ok, v := utils.InvokeFactoryVarFunc(id, nil); ok {
			strv := utils.GetStrValue(v, "")
			if isObject {
				replkey = fmt.Sprintf("\"%s%s%s\"", start, rawrepl, end)
			} else {
				replkey = fmt.Sprintf("%s%s%s", start, rawrepl, end)
				strv = utils.EscapeJsonStrSimple(strv)
			}
			s = strings.ReplaceAll(s, replkey, strv)
			continue
		}
		// 替换失败忽略
		idx++
	}

	return gobase.ReplacePlaceholder(s, "${", "}$", func(key string) (v string, ok bool) {
		return gobase.ParseSimpleExp(key)
	})
}
